package com.ollobot.authorization.security;

import com.ollobot.authorization.entity.User;
import com.ollobot.authorization.service.EmailVerificationService;
import com.ollobot.authorization.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
@Slf4j
public class EmailVerificationAuthenticationProvider implements AuthenticationProvider {

    private final EmailVerificationService emailVerificationService;
    private final UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        EmailVerificationAuthenticationToken token = (EmailVerificationAuthenticationToken) authentication;
        
        String email = token.getEmail();
        String code = token.getCode();
        
        // 验证邮箱验证码
        if (!emailVerificationService.verifyCode(email, code)) {
            throw new BadCredentialsException("Invalid verification code");
        }
        
        // 查找或创建用户
        User user = userService.findByEmail(email)
                .orElseGet(() -> {
                    // 如果用户不存在，创建新用户
                    String firstName = token.getFirstName();
                    String lastName = token.getLastName();
                    return userService.createUser(email, firstName, lastName);
                });
        
        log.info("Email verification authentication successful for: {}", email);
        
        return new EmailVerificationAuthenticationToken(
            user, null, user.getAuthorities(), email, code, 
            token.getFirstName(), token.getLastName()
        );
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return EmailVerificationAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
